package com.grace.common.utils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.grace.common.core.domain.TreeSelect;

public class TreeUtils {

    public static List<TreeSelect> buildTree(List<TreeSelect> ts) {
        List<TreeSelect> returnList = new ArrayList<TreeSelect>();
        List<Long> tempList = new ArrayList<Long>();
        for (TreeSelect treeSelect : ts) {
            tempList.add(treeSelect.getId());
        }
        for (TreeSelect treeSelect : ts) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(treeSelect.getParentId())) {
                recursionFn(ts, treeSelect);
                returnList.add(treeSelect);
            }
        }
        if (returnList.isEmpty()) {
            returnList = ts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private static void recursionFn(List<TreeSelect> list, TreeSelect t) {
        // 得到子节点列表
        List<TreeSelect> childList = getChildList(list, t);
        t.setChildren(childList);
        for (TreeSelect tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private static List<TreeSelect> getChildList(List<TreeSelect> list, TreeSelect t) {
        List<TreeSelect> tlist = new ArrayList<TreeSelect>();
        Iterator<TreeSelect> it = list.iterator();
        while (it.hasNext()) {
            TreeSelect n = (TreeSelect) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private static boolean hasChild(List<TreeSelect> list, TreeSelect t) {
        return getChildList(list, t).size() > 0;
    }

}
